package task

import (
	"errors"
	"strconv"
	"strings"

	"cvevulner/common"
	"cvevulner/taskhandler"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/config"
	"github.com/astaxie/beego/logs"
)

// GetIssueData  get the issue data
func GetIssueData() error {
	defer common.Catchs()
	logs.Info("The task of getting the data source of the created issue starts...")
	BConfig, err := config.NewConfig("ini", "conf/app.conf")
	if err != nil {
		logs.Error("config init error:", err)
		return err
	}
	communityName := beego.AppConfig.DefaultString("communityName", "src-openeuler:1")
	communityList := strings.Split(communityName, ",")
	for _, com := range communityList {
		comList := strings.Split(com, ":")
		if len(comList) == 2 {
			organizationID, err := strconv.Atoi(comList[1])
			if err != nil {
				logs.Error("err: ", err)
				continue
			}
			owner, giteeToken := common.GetOwnerAndToken("", int8(organizationID))
			// Synchronize gitee data to cve
			errx := taskhandler.GrabIssueByOrg(giteeToken, owner)
			if errx != nil {
				logs.Error("errx: ", errx)
			}
			logs.Info("The task of obtaining the data source of the created issue ends...")
			// The amount of data processed at a time
			prcNum, err := BConfig.Int("crontab::prcnum")
			if err != nil {
				logs.Error("crontab::prcnum, error:  ", err)
				return errors.New("value is nil")
			}
			// How many days have been processed to date data
			days, ok := BConfig.Int("crontab::days")
			if ok != nil {
				logs.Error("crontab::days, err:", err)
				return ok
			}
			// openeuler Number start value
			cveRef := BConfig.String("cve::cveref")
			openeulerNum, ok := BConfig.Int("cve::openeulernum")
			if ok != nil {
				logs.Error("cve::openeulernum, err:", err)
				return ok
			}
			logs.Info("Start syncing gitee data to the cve vulnerability database")
			// Compatible with created issue data
			oki, err := taskhandler.GetCveIssueData(prcNum, days, openeulerNum, cveRef, owner, 2)
			if !oki {
				logs.Error("ProcCveOriginData, GetCveIssueData, err: ", err)
			}
		}
	}
	logs.Info("End of syncing gitee data to cve vulnerability database")
	return err
}
